package com.RJAI.gemini.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import okhttp3.*;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
/*
作者信息
WeChat:ciansec
QQ:1068092013
 */
@Service
public class AsyncService {

    @Async
    public void asyncGemini(OkHttpClient.Builder clientBuilder, Request request, SseEmitter sseEmitter) {
        clientBuilder.connectTimeout(1000, TimeUnit.SECONDS).readTimeout(1000, TimeUnit.SECONDS).build().newCall(request).enqueue( new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println( "流式传输异常---->"+e.getMessage() );
                sseEmitter.completeWithError(e);
            }

            @Override
            protected Object clone() throws CloneNotSupportedException {
                return super.clone();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (okhttp3.ResponseBody responseBody = response.body()) {
                    System.out.println( "流式传输状态---->response.isSuccessful() = " + response.isSuccessful());
                    if (!response.isSuccessful() || responseBody == null){
                        sseEmitter.send(new BufferedReader(responseBody.charStream()).readLine(), MediaType.APPLICATION_JSON);
                        sseEmitter.complete();
                    };
                    BufferedReader reader = new BufferedReader(responseBody.charStream());
                    String line;
                    while ((line = reader.readLine()) != null ){
                        if (!StrUtil.isNotBlank( line )){
                            continue;
                        }
                        System.out.println( "流式接收数据----"+line);
                        System.out.println( "流式发送数据 " +("cian-"+line).replace( "cian-data: ","" ).replace( "cian-","" ) );
                        sseEmitter.send( SseEmitter.event().data(" "+("cian-"+line).replace( "cian-data: ","" ).replace( "cian-","" )));
                    }
                    System.out.println( "流式传输结束---->");
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    sseEmitter.complete();
                }
            }
        });

    }


    @Async
    public void asyncClaude(OkHttpClient.Builder clientBuilder, Request request, SseEmitter sseEmitter, HashMap<String,Integer> status) {
        clientBuilder.connectTimeout(1000, TimeUnit.SECONDS).readTimeout(1000, TimeUnit.SECONDS).build().newCall(request).enqueue( new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                status.put( "status",-1);
                System.out.println( "流式传输异常---->"+e.getMessage() );
                sseEmitter.completeWithError(e);
            }

            @Override
            protected Object clone() throws CloneNotSupportedException {
                return super.clone();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String eventName="";
                try (okhttp3.ResponseBody responseBody = response.body()) {

                    System.out.println( "流式传输状态---->response.isSuccessful() = " + response.isSuccessful());
                    if (response.isSuccessful()){
                        BufferedReader reader = new BufferedReader(responseBody.charStream());
                        String line;
                        while ((line = reader.readLine()) != null ){

                            if (!StrUtil.isNotBlank( line )){
                                continue;
                            }
                            if ("\n".equals( line ) || "\r".equals( line )){
                                continue;
                            }

                            System.out.println( "流式接收数据----"+line);
                            if (line.startsWith( "event:" )){
                                line=line.substring(7);
                                eventName=line;
                                if ("error".equals(eventName)){
                                    status.put( "status",-1);
                                    return;
                                }
                                //sseEmitter.send( SseEmitter.event().name(line));
                            }
                            if (!status.containsKey("status")){
                                status.put( "status",1);
                                try {
                                    Thread.sleep( 80 );
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                            }
                            if (line.startsWith( "data: " )){
                                line=line.substring(6);
                                sseEmitter.send( SseEmitter.event().name( " "+eventName ).data(" "+line.replace("msg_vrtx_","msg_"),MediaType.APPLICATION_JSON));
                            }

                        }
                    }else {
                        status.put( "status",-1);

                    }


                    System.out.println( "流式传输结束---->");
                }catch (Exception e){
                    status.put( "status",-1);
                    try {
                        Thread.sleep( 80 );
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    e.printStackTrace();
                }finally {
                    if (!status.containsKey("status")){
                        status.put( "status",-1);
                    }

                    try {
                        Thread.sleep( 80 );
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    sseEmitter.complete();
                }
            }
        });

    }

    @Async
    public void sstTest(OkHttpClient.Builder clientBuilder, Request request, SseEmitter sseEmitter) {
        clientBuilder.connectTimeout(1000, TimeUnit.SECONDS).readTimeout(1000, TimeUnit.SECONDS).build().newCall(request).enqueue( new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println( "流式传输异常---->"+e.getMessage() );
                sseEmitter.completeWithError(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (okhttp3.ResponseBody responseBody = response.body()) {
                    System.out.println( "流式传输状态---->response.isSuccessful() = " + response.isSuccessful());
                    if (!response.isSuccessful() || responseBody == null){
                        sseEmitter.send(new BufferedReader(responseBody.charStream()).readLine());
                        sseEmitter.complete();
                    };
                    BufferedReader reader = new BufferedReader(responseBody.charStream());
                    String line;
                    while ((line = reader.readLine()) != null){
                        System.out.println( "流式接收数据---->line = " + ("cian-"+line).replace( "cian-data: ","" ).replace( "cian-" ,""));
                        sseEmitter.send(line);
                    }
                    System.out.println( "流式传输结束---->");
                    sseEmitter.complete();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

    }
}